class WxRequest {
  defaults = {
    //baseURL: 'https://security.dfteco.com', // 请求基准地址
    baseURL: 'http://192.168.2.202:8888', // 请求基准地址
    url: '', // 接口的请求路径
    data: null, // 请求参数
    method: 'GET', // 默认的请求方法
    header: {
      'Content-type': 'application/json' // 设置数据的交互格式
    },
    timeout: 60000, // 默认的超时时长，小程序默认的超时时长是 1 分钟
    isLoading: false // 控制是否使用默认的 loading，默认值是 true 表示使用默认的 loading
  }

  interceptors = {
    request: (config) => {
      const token = wx.getStorageSync('token')
      const tenant = wx.getStorageSync('tenantCode')
      if (token) {
        config.header['X-token'] = `${token}`
        config.header['tenant'] = `${tenant}`
      }
      return config
    },
    // response: (response) => response.data
    response: (response) => {
      let {
        data
      } = response
      if (wx.getStorageSync('version')) {
        console.log(wx.getStorageSync('version'),data.version,'1');
        if (wx.getStorageSync('version') !== data.version) {
          console.log(wx.getStorageSync('version'),data.version,'2');
          wx.restartMiniProgram({
            path: "/pages/start/index",
            success: function () {
              wx.showToast({
                title: '检查到新版本,正在重启',
                icon:'none',
                duration: 1500
              })
              wx.setStorageSync('version', data.version)
              return
            }
          })
          return
        }
      }
      wx.setStorageSync('version', data.version)
      // console.log(data, '相应拦截器');
      switch (data.code) {
        case 0:
          return data
        case 1:
          wx.showToast({
            title: data.message || '未知错误',
            icon: 'error',
            duration: 2000
          })
          return Promise.reject(response)
        case 403:
          wx.showToast({
            title: data.message || '未知错误',
            icon: 'error',
            duration: 2000
          })
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/login/index',
            })
          }, 2000)
          return
        default:
          return Promise.reject(response)
      }
    }
  }

  queue = []

  constructor(params = {}) {
    this.defaults = Object.assign({}, this.defaults, params)
  }

  request(options) {
    this.timerId && clearTimeout(this.timerId)
    options.url = this.defaults.baseURL + options.url
    options = {
      ...this.defaults,
      ...options
    }
    if (options.isLoading && options.method !== 'UPLOAD') {
      this.queue.length === 0 && wx.showLoading()
      this.queue.push('request')
    }
    options = this.interceptors.request(options)
    return new Promise((resolve, reject) => {
      if (options.method === 'UPLOAD') {
        wx.uploadFile({
          ...options,
          success: (res) => {
            res.data = JSON.parse(res.data)
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true
            })
            resolve(this.interceptors.response(mergeRes))
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false
            })
            reject(this.interceptors.response(mergeErr))
          }
        })
      } else {
        wx.request({
          ...options,
          success: (res) => {
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true
            })
            resolve(this.interceptors.response(mergeRes))
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false
            })
            reject(this.interceptors.response(mergeErr))
          },
          complete: () => {
            if (options.isLoading) {
              this.queue.pop()
              this.queue.length === 0 && this.queue.push('request')
              this.timerId = setTimeout(() => {
                this.queue.pop()
                this.queue.length === 0 && wx.hideLoading()
                clearTimeout(this.timerId)
              }, 1)
            }
          }
        })
      }
    })
  }
  get(url, data = {}, config = {}) {
    return this.request(Object.assign({
      url,
      data,
      method: 'GET'
    }, config))
  }

  delete(url, data = {}, config = {}) {
    return this.request(Object.assign({
      url,
      data,
      method: 'DELETE'
    }, config))
  }

  post(url, data = {}, config = {}) {
    return this.request(Object.assign({
      url,
      data,
      method: 'POST'
    }, config))
  }

  put(url, data = {}, config = {}) {
    return this.request(Object.assign({
      url,
      data,
      method: 'PUT'
    }, config))
  }

  all(...promise) {
    return Promise.all(promise)
  }

  upload(url, filePath, name = 'file', config = {}) {
    return this.request(
      Object.assign({
        url,
        filePath,
        name,
        method: 'UPLOAD'
      }, config)
    )
  }
}
const http = new WxRequest()
export default http